All files / local persistence_promise.ts

84.81% Statements 67/79
83.33% Branches 15/18
85.19% Functions 23/27
83.78% Lines 62/74
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204                                2x                                               2x       282979x   282979x     282979x 282979x 282979x       282979x   282979x 282979x   282949x 282949x 282949x     79765x       30x 30x 30x 14x           2x     6946x     186730x       186730x     186730x 186730x 106951x 106935x   16x     79779x 79779x 79765x   79779x 14x           15036x 15036x 15036x       2x     179794x 179794x 179783x 50793x   128990x     11x       2x       186700x 179765x         6935x       2x       30x 29x   1x           2x 181524x 181524x       2x 16x 16x       2x       17565x 9608x 9608x         2x                                         2x  
/**
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import { fail } from '../util/assert';
 
export type FulfilledHandler<T, R> =
  | ((result: T) => R | PersistencePromise<R>)
  | null;
export type RejectedHandler<R> =
  | ((reason: Error) => R | PersistencePromise<R>)
  | null;
export type Resolver<T> = (value?: T) => void;
export type Rejector = (error: Error) => void;
 
/**
 * PersistencePromise<> is essentially a re-implementation of Promise<> except
 * it has a .next() method instead of .then() and .next() and .catch() callbacks
 * are executed synchronously when a PersistencePromise resolves rather than
 * asynchronously (Promise<> implementations use setImmediate() or similar).
 *
 * This is necessary to interoperate with IndexedDB which will automatically
 * commit transactions if control is returned to the event loop without
 * synchronously initiating another operation on the transaction.
 *
 * NOTE: .then() and .catch() only allow a single consumer, unlike normal
 * Promises.
 */
export class PersistencePromise<T> {
  // NOTE: next/catchCallback will always point to our own wrapper functions,
  // not the user's raw next() or catch() callbacks.
  // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.
  private nextCallback: FulfilledHandler<T, any> = null;
  // tslint:disable-next-line:no-any Accept any result type for the error handler.
  private catchCallback: RejectedHandler<any> = null;
 
  // When the operation resolves, we'll set result or error and mark isDone.
  private result: T | undefined = undefined;
  private error: Error | undefined = undefined;
  private isDone = false;
 
  // Set to true when .then() or .catch() are called and prevents additional
  // chaining.
  private callbackAttached = false;
 
  constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void) {
    callback(
      value => {
        this.isDone = true;
        this.result = value;
        if (this.nextCallback) {
          // value should be defined unless T is Void, but we can't express
          // that in the type system.
          this.nextCallback(value!);
        }
      },
      error => {
        this.isDone = true;
        this.error = error;
        if (this.catchCallback) {
          this.catchCallback(error);
        }
      }
    );
  }
 
  catch<R>(
    fn: (error: Error) => R | PersistencePromise<R>
  ): PersistencePromise<R> {
    return this.next(undefined, fn);
  }
 
  next<R>(
    nextFn?: FulfilledHandler<T, R>,
    catchFn?: RejectedHandler<R>
  ): PersistencePromise<R> {
    Iif (this.callbackAttached) {
      fail('Called next() or catch() twice for PersistencePromise');
    }
    this.callbackAttached = true;
    if (this.isDone) {
      if (!this.error) {
        return this.wrapSuccess(nextFn, this.result!);
      } else {
        return this.wrapFailure(catchFn, this.error);
      }
    } else {
      return new PersistencePromise<R>((resolve, reject) => {
        this.nextCallback = (value: T) => {
          this.wrapSuccess(nextFn, value).next(resolve, reject);
        };
        this.catchCallback = (error: Error) => {
          this.wrapFailure(catchFn, error).next(resolve, reject);
        };
      });
    }
  }
 
  toPromise(): Promise<T> {
    return new Promise((resolve, reject) => {
      this.next(resolve, reject);
    });
  }
 
  private wrapUserFunction<R>(
    fn: () => R | PersistencePromise<R>
  ): PersistencePromise<R> {
    try {
      const result = fn();
      if (result instanceof PersistencePromise) {
        return result;
      } else {
        return PersistencePromise.resolve(result);
      }
    } catch (e) {
      return PersistencePromise.reject<R>(e);
    }
  }
 
  private wrapSuccess<R>(
    nextFn: FulfilledHandler<T, R> | undefined,
    value: T
  ): PersistencePromise<R> {
    if (nextFn) {
      return this.wrapUserFunction(() => nextFn(value));
    } else {
      // If there's no nextFn, then R must be the same as T but we
      // can't express that in the type system.
      // tslint:disable-next-line:no-any
      return PersistencePromise.resolve<R>(value as any);
    }
  }
 
  private wrapFailure<R>(
    catchFn: RejectedHandler<R> | undefined,
    error: Error
  ): PersistencePromise<R> {
    if (catchFn) {
      return this.wrapUserFunction(() => catchFn(error));
    } else {
      return PersistencePromise.reject<R>(error);
    }
  }
 
  static resolve(): PersistencePromise<void>;
  static resolve<R>(result: R): PersistencePromise<R>;
  static resolve<R>(result?: R): PersistencePromise<R | void> {
    return new PersistencePromise<R>((resolve, reject) => {
      resolve(result);
    });
  }
 
  static reject<R>(error: Error): PersistencePromise<R> {
    return new PersistencePromise<R>((resolve, reject) => {
      reject(error);
    });
  }
 
  static waitFor(
    // tslint:disable-next-line:no-any Accept all Promise types in waitFor().
    all: Array<PersistencePromise<any>>
  ): PersistencePromise<void> {
    return all.reduce((promise, nextPromise, idx) => {
      return promise.next(() => {
        return nextPromise;
      });
    }, PersistencePromise.resolve());
  }
 
  static map<R>(all: Array<PersistencePromise<R>>): PersistencePromise<R[]> {
    const results: R[] = [];
    let first = true;
    // initial is ignored, so we can cheat on the type.
    // tslint:disable-next-line:no-any
    const initial = PersistencePromise.resolve<R>(null as any);
    return all
      .reduce((promise, nextPromise) => {
        return promise.next(result => {
          if (!first) {
            results.push(result);
          }
          first = false;
          return nextPromise;
        });
      }, initial)
      .next(result => {
        results.push(result);
        return results;
      });
  }
}